<template>
  <el-dialog :width="600" destroy-on-close draggable title="Upload File" v-model="dialogUploadFileFormVisible">
    <el-upload multiple :action=props.uploadFileUrl :before-upload="handleBeforeUpload" :file-list="fileList"
      :limit="limit" :on-error="handleUploadError" :on-exceed="handleExceed" :on-success="handleUploadSuccess"
      :show-file-list="false" :headers="headers" class="upload-file-uploader" :accept="props.fileType" ref="fileUpload" :data="uploadData"
      style="display: inline-block;">
      <!-- 上传按钮 -->
      <el-button type="primary">Choose File</el-button>
    </el-upload>
    <div v-if="isDownTemplate">
      <a v-if="props.isAlink" :href="props.url" class="bullshit__return-home"
        style="color: #409eff; margin-left: 20px">{{
        $t("ship.button.downloadTemplate")
        }}</a>
      <el-button v-else type="text" style="margin-left: 20px" @click="downTemplate">
        {{$t("ship.button.downloadTemplate")}}</el-button>
    </div>
    <!-- 下载模板按钮 -->

    <!-- 上传提示 -->
    <div class="el-upload__tip" v-if="showTip">
      Please upload File
      <template v-if="fileSize"> Not more than <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
      <template v-if="fileType"> The file format is <b style="color: #f56c6c">{{ getTypeStr(fileType) }}</b> </template>
    </div>
    <!-- 文件列表 -->
    <transition-group class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear" tag="ul">
      <li :key="file.uid" class="el-upload-list__item ele-upload-list__item-content" v-for="(file, index) in fileList">
        <el-link :href="file.url" :underline="false" target="_blank">
          <span class="el-icon-document"> {{ getFileName(file.name) }} </span>
        </el-link>
        <div class="ele-upload-list__item-content-action">
          <el-link :underline="false" @click="handleDelete(index)" type="danger">删除</el-link>
        </div>
      </li>
    </transition-group>
  </el-dialog>
</template>

<script setup>
  import { getToken } from "@/utils/auth";
  import { downloadFile } from "@/utils/downloadFile";
  const props = defineProps({
    modelValue: [String, Object, Array],
    // 数量限制
    limit: {
      type: Number,
      default: 5,
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 1,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => [".doc", ".xls", ".ppt", ".txt", ".pdf"],
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true
    },
    isAlink: {
      type: Boolean,
      default: true
    },
    isDownTemplate: {
      type: Boolean,
      default: true
    },
    uploadFileUrl: {
      type: String,
      default: ""
    },
    queryParams: {
      type: Object,
      default: () => {
        return {};
      }
    },
    uploadData: {
      type: Object,
      default: () => {
        return {};
      }
    },
    templateFile: {
      type: String,
      default: "Template.xlsx"
    },
    url: {
      type: String,
      default: "https://booking-1257832417.cos.ap-nanjing.myqcloud.com/template/vehicleTemplate.xlsx"

    }
  });

  const { proxy } = getCurrentInstance();
  const emit = defineEmits();
  const number = ref(0);
  const uploadList = ref([]);
  const baseUrl = import.meta.env.VITE_APP_BASEURL;
  //const uploadFileUrl = ref(baseUrl + "/file/upload"); // 上传文件服务器地址
  const headers = ref({ authentication: getToken() });
  const fileList = ref([]);
  const dialogUploadFileFormVisible = ref(false);
  const dialogUploadFileForm = () => {
    dialogUploadFileFormVisible.value = true;
  }
  defineExpose({ dialogUploadFileForm })
  const showTip = computed(
    () => props.isShowTip && (props.fileType || props.fileSize)
  );

  watch(() => props.modelValue, val => {
    if (val) {
      let temp = 1;
      // 首先将值转为数组
      const list = Array.isArray(val) ? val : props.modelValue.split(',');
      // 然后将数组转为对象数组
      fileList.value = list.map(item => {
        if (typeof item === "string") {
          item = { name: item, url: item };
        }
        item.uid = item.uid || new Date().getTime() + temp++;
        return item;
      });
    } else {
      fileList.value = [];
      return [];
    }
  }, { deep: true, immediate: true });

  // 上传前校检格式和大小
  function handleBeforeUpload(file) {
    // 校检文件类型
    if (props.fileType.length) {
      const fileName = file.name.split('.');
      const fileExt = fileName[fileName.length - 1];
      const isTypeOk = props.fileType.indexOf('.'+ fileExt) >= 0;
      if (!isTypeOk) {
        proxy.$modal.msgError(`The file format is incorrect, please upload it ${ getTypeStr(props.fileType)} Format file!`);
        return false;
      }
    }
    // 校检文件名是否包含特殊字符
    if (file.name.includes(',')) {
      proxy.$modal.msgError('The file name is incorrect and cannot contain English commas!');
      return false;
    }
    // 校检文件大小
    if (props.fileSize) {
      const isLt = file.size / 1024 / 1024 < props.fileSize;
      if (!isLt) {
        proxy.$modal.msgError(`The size of the uploaded file cannot exceed ${props.fileSize} MB!`);
        return false;
      }
    }
    proxy.$modal.loading("Uploading files, please wait...");
    number.value++;
    return true;
  }

  // 文件个数超出
  function handleExceed() {
    proxy.$modal.msgError(`上传文件数量不能超过 ${props.limit} 个!`);
  }

  // 上传失败
  function handleUploadError(err) {
    // proxy.$modal.msgError("上传文件失败");
    proxy.$modal.msgError("upload file failed");
  }

  // 上传成功回调
  function handleUploadSuccess(res, file) {
    if (res.code === 200) {
      uploadList.value.push({ name: res.data.url, url: res.data.url });
      dialogUploadFileFormVisible.value = false;
      if(res.msg){
        proxy.$modal.msgSuccess(res.msg);
      }
      uploadedSuccessfully();
    } if (res.code === 0) {
      uploadList.value = res.data||[]
      dialogUploadFileFormVisible.value = false;
      if(res.msg){
        proxy.$modal.msgSuccess(res.msg);
      }
      uploadedSuccessfully();
    } else {
      number.value--;
      proxy.$modal.msgError(res.message || res.data);
      proxy.$refs.fileUpload.handleRemove(file);
      proxy.$modal.closeLoading();
      setTimeout(() => {
        dialogUploadFileFormVisible.value = false;
      }, 500)

    }

  }

  // 删除文件
  function handleDelete(index) {
    fileList.value.splice(index, 1);
    emit("update:modelValue", listToString(fileList.value));
  }

  // 上传结束处理
  function uploadedSuccessfully() {
    if (number.value > 0 && uploadList.value?.length === number.value) {
      fileList.value = fileList.value.filter(f => f.url !== undefined).concat(uploadList.value);
      uploadList.value = [];
      number.value = 0;
      emit("update:modelValue", listToString(fileList.value));
      proxy.$modal.closeLoading();
      fileList.value=[]
    }else{
      emit("update:modelValue", listToString(fileList.value));
      proxy.$modal.closeLoading();
    }
  }

  // 获取文件名称
  function getFileName(name) {
    // 如果是url那么取最后的名字 如果不是直接返回
    if (name.lastIndexOf("/") > -1) {
      return name.slice(name.lastIndexOf("/") + 1);
    } else {
      return name;
    }
  }

   // 获取文件名称
   function getTypeStr(list,separator) {
    let strs = "";
    separator = separator || ",";
    for (let i in list) {
      if (list[i]) {
        strs += list[i].split('.').pop() + separator;
      }
    }
    return strs != "" ? strs.substr(0, strs.length - 1) : "";
  }

  // 对象转成指定字符串分隔
  function listToString(list, separator) {
    let strs = "";
    separator = separator || ",";
    for (let i in list) {
      if (list[i].url) {
        strs += list[i].url + separator;
      }
    }
    return strs != "" ? strs.substr(0, strs.length - 1) : "";
  }
  const downTemplate = () => {
    downloadFile(props.url, props.queryParams, props.templateFile);
  };
</script>

<style scoped lang="scss">
  .upload-file-uploader {
    margin-bottom: 5px;
  }

  .upload-file-list .el-upload-list__item {
    border: 1px solid #e4e7ed;
    line-height: 2;
    margin-bottom: 10px;
    position: relative;
  }

  .upload-file-list .ele-upload-list__item-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: inherit;
  }

  .ele-upload-list__item-content-action .el-link {
    margin-right: 10px;
  }
</style>